<template>
  <div class="comment-container">
    <!-- 评论表单 -->
    <CommentForm
        :parentId="currentParentId"
        @submit-comment="handleSubmit"
        @cancel-reply="cancelReply"
    />

    <!-- 评论列表 -->
    <div class="comment-list">
      <CommentItem
          v-for="comment in comments"
          :key="comment.id"
          :comment="comment"
          @reply="handleReply"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import CommentForm from '@/views/CommentForm.vue'
import CommentItem from '@/views/CommentItem.vue'

const props = defineProps(['id'])
const comments = ref([])
const currentParentId = ref(null)

// 加载评论
const loadComments = async () => {
  try {
    const res = await request.get(`/comment/list?postId=${props.id}`)
    comments.value = buildCommentTree(res.data)
  } catch (error) {
    console.error('加载评论失败:', error)
  }
}

// 构建评论树形结构
const buildCommentTree = (flatComments) => {
  const map = {}
  const tree = []

  flatComments.forEach(comment => {
    map[comment.id] = { ...comment, children: [] }
    if (comment.parentId && map[comment.parentId]) {
      map[comment.parentId].children.push(map[comment.id])
    } else {
      tree.push(map[comment.id])
    }
  })

  return tree
}

// 处理回复
const handleReply = (parentId) => {
  currentParentId.value = parentId
}

// 提交评论
const handleSubmit = async (content) => {
  try {
    await request.post('/comment/create', {
      postId: props.id,
      content,
      parentId: currentParentId.value
    })
    await loadComments()
    currentParentId.value = null
  } catch (error) {
    console.error('提交评论失败:', error)
  }
}

// 取消回复
const cancelReply = () => {
  currentParentId.value = null
}

onMounted(() => {
  loadComments()
})
</script>

<style scoped>
.comment-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
}
.comment-list {
  margin-top: 30px;
}
</style>